package cn.xw.mq.producer;

import cn.xw.config.RabbitMQConfig;
import cn.xw.entity.MessageSendDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-14 21:39
 * 测试生产者
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TestProducer {

    //注入rabbitTemplate对象
    private final RabbitTemplate rabbitTemplate;

    /***
     * 生产者方法
     * @param msg 消息
     */
    public void producerSendMsg(MessageSendDTO msg) {
        //循环发送投递消息
        for (int i = 1001; i <= 1010; i++) {
            msg.setMsgID(i);
            //消息转换为JSON格式并转为字节数组
            byte[] bytes = JSONObject.toJSONString(msg).getBytes(StandardCharsets.UTF_8);
            //若i为1005则代表让它的消息优先级高，其它都是默认0
            if (i == 1005) {
                //设置其它参数（如这里需要设置优先级)（2种参数方式）
                //AMQP.BasicProperties properties = new AMQP.BasicProperties();
                //properties.builder().priority(5).build();
                MessageProperties messageProperties = new MessageProperties();
                messageProperties.setPriority(5);
                //发送消息
                Message message = new Message(bytes, messageProperties);
                rabbitTemplate.convertAndSend(RabbitMQConfig.ORDINARY_DIRECT_EXCHANGE,
                        RabbitMQConfig.ROUTE_KEY, message);
            } else {
                //发送消息
                rabbitTemplate.convertAndSend(RabbitMQConfig.ORDINARY_DIRECT_EXCHANGE,
                        RabbitMQConfig.ROUTE_KEY, bytes);
            }
        }
    }
}
